﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.HomeServer.Controls;
using RouterControl.IO;
using RouterControl.IO.UPnP;
using RouterControl.Whs;
using RouterControl.Whs.Wizards;
using RouterControl.WhsAddIn.Wizards.SelectRouter.FeatureTests;

namespace RouterControl.WhsAddIn.Wizards.SelectRouter
{
    public partial class PageFeatureTest : WizardPageClientBannerTop
    {
        private readonly log4net.ILog _log = log4net.LogManager.GetLogger(typeof(PageFeatureTest));
        private IUPnPDevice _selectedDevice;
        private CommonInternetGateway _selectedRouter;

        private WizardMain ParentWizardMain
        {
            get { return (WizardMain)this.ParentWizard; }
        }

        public PageFeatureTest()
        {
            InitializeComponent();
        }

        private void PageFeatureTest_BackButtonClick(object sender, EventArgs e)
        {
            this.SetCurrentPage<PageRouterList>();
        }

        private void PageFeatureTest_OkButtonClick(object sender, EventArgs e)
        {
            // select device then
            this.ParentWizardMain.Settings.SelectedRouterDeviceUniqueName = _selectedDevice.UniqueDeviceName;

            // continue
            this.ParentWizardMain.DialogResult = DialogResult.OK;

            this.ParentWizard.Close();
        }

        private void diagList_OnDiagnosisDone(object sender, DiagList.DiagnosisDoneEventArgs e)
        {
            this.BackButtonEnabled = true;
            this.CancelButtonEnabled = true;
            this.OkButtonEnabled = true;

            this.labelResult.Text = string.Format(
                (e.Result != DiagList.DiagResult.Successful) ?
                Resources.txtFeatureTestFailed :
                Resources.txtFeatureTestAccomplished,
                this.ParentWizardMain.SelectedDevice.FriendlyName
                );
        }

        public override void StartRealWork()
        {
            base.StartRealWork();

            // prepare
            _selectedDevice = this.ParentWizardMain.SelectedDevice;

            // get usage info
            var dev = this.ParentWizardMain.SelectedDevice;

            if (dev == null)
                throw new Exception("no device selected");

            // gather information
            var info = this.ParentWizardMain.UsageInfo;

            info.ExitPage = GetType().Name;

            var ui = info.EnsureRouterInfo(dev.CreateSchemaId(), false);

            ui.ExitPage = GetType().Name;

            // create device
            try
            {
                var router = new RootDevice(dev);

                _selectedRouter = new CommonInternetGateway(router);

                ui.SupportedManaged = true;
            }
            catch (Exception x)
            {
                _log.Error(string.Format(
                    "Failed to create managed UPNP device: {0} ({1})",
                    _selectedDevice.FriendlyName,
                    _selectedDevice.UniqueDeviceName
                    ), x);

                ui.SupportedManaged = false;

                QMessageBox.Show(
                    string.Format(Resources.txtManagedFailedText, _selectedDevice.FriendlyName),
                    Resources.txtManagedFailedTitle,
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error
                    );

                this.SetCurrentPage<PageRouterList>();
            }

            // add diagnosis
            this.diagList.ClearAllDiagnosises();
            this.diagList.AddDiagnosis(new FeatureTestConnectionStatus(_selectedRouter, ui));
            this.diagList.AddDiagnosis(new FeatureTestConnectionSpeed(_selectedRouter, ui));
            this.diagList.AddDiagnosis(new FeatureTestUptime(_selectedRouter, ui));
            this.diagList.AddDiagnosis(new FeatureTestTraffic(_selectedRouter, ui));
            this.diagList.AddDiagnosis(new FeatureTestHijackingDetection(_selectedRouter, ui));
            this.diagList.AddDiagnosis(new FeatureTestPortForwarding(_selectedRouter, ui));

            // run diagnosis
            this.diagList.RunDiagnosisAsync();
        }
    }
}